<template>
  <div class="profile-edit-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/profileT" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">编辑资料</h5>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
        <!-- 头像 -->
        <div class="avatar-section text-center mb-4">
          <div class="avatar mx-auto">
            <img v-if="form.imagePath" :src="form.imagePath" alt="用户头像">
            <label for="avatarInput" class="avatar-edit" @click.prevent="selectAvatar">
              <i class="bi bi-camera"></i>
            </label>
            <input type="file" id="avatarInput" style="display: none" @change="handleAvatarChange">
          </div>
        </div>

      <!-- 基本信息表单 -->
      <div class="form-group mb-3">
        <label class="form-label">姓名</label>
        <input
          type="text"
          class="form-control"
          v-model="form.realName"
          placeholder="请输入姓名"
        >
      </div>

      <div>
        <label class="form-label">考研年份</label>
        <select class="form-select" v-model="form.userLevel">
          <option v-for="year in years" :key="year" :value="year">{{year}}</option>
        </select>
      </div>
      <div class="form-group mb-3">
        <label class="form-label">年龄</label>
        <input
            type="text"
            class="form-control"
            v-model="form.age"
            placeholder="请输入年龄"
        >
      </div>
      <div class="form-group mb-3">
        <label class="form-label">性别</label>
        <select class="form-select" v-model="form.sex" :disabled="isDisabled">
          <option value="1">男</option>
          <option value="2">女</option>
        </select>
      </div>
      <div class="form-group mb-3">
        <label class="form-label">出生日期</label>
        <div>
          <date-picker
                v-model="form.birthDay"
                :format="'YYYY-MM-DD'"
                :show-time="false"
                :editable="false"
                :clearable="false"
          />
        </div>
      </div>
      <div class="form-group mb-3">
        <label class="form-label">手机号</label>
        <input
            type="text"
            class="form-control"
            v-model="form.phone"
            placeholder="请输入手机号"
        >
      </div>
      <div class="form-group mb-3">
        <label class="form-label">是否允许老师监督学习</label>
        <div>
          <input type="radio" id="supervision" value="1" v-model="form.supervision" />
          <label for="supervisionYes">允许</label>
          <input type="radio" id="supervision" value="0" v-model="form.supervision" />
          <label for="supervisionNo">不允许</label>
        </div>
      </div>
      <div class="form-group mb-3">
        <label class="form-label">目标专业</label>
        <input
          type="text"
          class="form-control"
          v-model="form.targetMajor"
          placeholder="请输入目标专业"
        >
      </div>

      <div class="form-group mb-3">
        <label class="form-label">目标院校</label>
        <input
          type="text"
          class="form-control"
          v-model="form.targetUniversity"
          placeholder="请输入目标院校"
        >
      </div>

      <!-- 保存按钮 -->
      <button
        class="btn btn-primary w-100 mt-4"
        @click="saveProfile"
      >保存修改</button>
    </div>
  </div>
</template>

<script>
// export default {
//   name: 'ProfileEditView',
//   data() {
//     return {
//       form: {
//         avatar: 'images/avatar.jpg',
//         name: '张同学',
//         year: '2024',
//         major: '计算机专业',
//         targetSchool: ''
//       }
//     }
//   },
//   methods: {
//     selectAvatar() {
//       // TODO: 实现头像选择功能
//       console.log('选择头像')
//     },
//     saveProfile() {
//       // TODO: 实现保存个人资料功能
//       console.log('保存资料:', this.form)
//       this.$router.push('/profile')
//     }
//   }
// }
import axios from 'axios'; // 引入axios用于网络请求
import http from "@/router/http"; // 引入日历组件的样式文件
import { getUserByToken } from '@/config/api.js';
import GenderSelect from '../../common/GenderSelect.vue';
import DatePicker from 'vue3-datepicker';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);
export default {
  name: 'ProfileEditView',
  components: {
    GenderSelect,
    DatePicker
  },
  data() {
    const currentYear = new Date().getFullYear()+10;
    const startYear =  new Date().getFullYear()-10; // 可以按需调整起始年份
    const years = [];
    for (let year = startYear; year <= currentYear; year++) {
      years.push(year);
    }
    return {
      form: {
        userId: '',
        imagePath: '',
        realName: '',
        userLevel: '',
        targetMajor: '',
        targetUniversity: '',
        phone: '',
        age: '',
        sex: '',
        birthDay: dayjs().utc().local().format('YYYY-MM-DD')
      },
      years,
      userGender: '', // 初始值可按需设置
    }
  },
  mounted() {
    this.fetchProfileData(); // 在组件挂载时调用获取用户资料数据的方法
  },
  methods: {
    async fetchProfileData() {
      try {
        //获取当前用户信息
        const userData = await getUserByToken();
        const user = userData.response;
        const response = await http.get(`/userToken/getUserById/${user.userId}`);
        if (response.status === 200 && response.data && response.data.response) {
          this.form = response.data.response; // 将后端返回的数据赋值给form对象，填充表单数据
          if(response.data.response.birthDay){
            // 先将后端返回的日期字符串转换为dayjs对象，并明确设置其所在时区（假设后端返回的是带时区信息的格式，比如ISO 8601格式）
            const dateObj = dayjs(response.data.response.birthDay).utc().local();
            // 将其格式化为符合要求的字符串（这里还是'YYYY-MM-DD'格式），以 UTC 时间为准
            this.form.birthDay = new Date(dateObj.format('YYYY-MM-DD HH:mm:ss'));
            this.form.supervision = response.data.response.supervision;
            const baseUrl = http.defaults.baseURL || "";
            if(response.data.response.imagePath){
              this.form.imagePath = baseUrl+"/uploadPath" + response.data.response.imagePath;
            }
          }
        }
      } catch (error) {
        console.error('获取用户资料数据失败:', error);
      }
    },
    selectAvatar() {
      // 通过触发隐藏的文件选择input元素来打开文件选择框
      document.getElementById('avatarInput').click();
    },
    async handleAvatarChange(event) {
        const file = event.target.files[0];
        if (file) {
          // 验证图片文件格式，可根据实际需求调整白名单
          const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'];
          if (!allowedFormats.includes(file.type)) {
            alert('请选择正确的图片格式（支持 JPEG、PNG、GIF）');
            return;
          }
          const reader = new FileReader();
          reader.onload = () => {
            this.form.imagePath = reader.result;
          };
          reader.readAsDataURL(file);
          const formData = new FormData();
          formData.append('file', file);
          // formData.append('userId', localStorage.getItem('userId'));
          const response = await http.post('/admin/upload/file', formData);
          if (response.status === 200) {
            console.log('头像上传成功');
            const baseUrl = http.defaults.baseURL || "";
            this.form.imagePath = baseUrl +"/uploadPath"+response.data;
          } else {
            console.error('头像上传失败:', response.data.message);
          }
        }
    },
    async saveProfile() {
      try {
        // this.form.birthDay = dayjs(this.form.birthDay).utc().local().format('YYYY-MM-DD HH:mm:ss');
        const  requestData = {
          userId: this.form.userId,
          realName: this.form.realName,
          userLevel: this.form.userLevel,
          targetMajor: this.form.targetMajor,
          targetUniversity: this.form.targetUniversity,
          phone: this.form.phone,
          age: this.form.age,
          sex: this.form.sex,
          supervision: this.form.supervision,
          imagePath: this.form.imagePath!== "" && this.form.imagePath!== null ? this.form.imagePath.replace(http.defaults.baseURL + "/uploadPath",""):null,
          birthDay: this.form.birthDay!== "" && this.form.birthDay !== null ? dayjs(this.form.birthDay).utc().local().format('YYYY-MM-DD HH:mm:ss'):null
        };
        const response = await http.post('/student/user/edit', requestData);
        if (response.status === 200) {
          console.log('个人信息保存成功');
          this.$router.push('/profileT'); // 保存成功后跳转到个人资料页面
        }
      } catch (error) {
        console.error('保存个人信息失败:', error);
      }
    }
  }
}
</script>

<style scoped>
/* 可以在这里添加针对radio按钮的样式调整，比如间距、大小等 */
label {
  margin-right: 10px;
}
.my-calendar {
  height: 400px;
}
.profile-edit-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.form-container {
  padding: 20px;
}

.avatar-section .avatar {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid rgba(0,184,169,0.3);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0,0,0,0.5);
  color: white;
  padding: 5px;
  cursor: pointer;
}

.form-group label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 8px;
}
</style> 